package net.yebaihe.wc;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.HashMap;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

public class OfflineDataMan extends DataMan {

	OfflineDataMan(){
	}
	
	public void initdata() {
		SQLiteDatabase db = MyHelper.get(ctx).getWritableDatabase();
		if (db!=null){
			Cursor c=db.rawQuery("select count(*) from restaurants", null);
			c.moveToFirst();
			if (c.getInt(0)<=0){
				db.execSQL("delete from restaurants", new Object[]{});
				db.execSQL("INSERT INTO restaurants (_id,name,city,avgprice,lon,lat,discount,discountdesc,addr,tel,zone,subzone) VALUES (1,'唐都生态园','太原',103,112.552924,37.805654,20,'满100减20','平阳路398号','03517025070',11,9)"); 
				db.execSQL("INSERT INTO restaurants (_id,name,city,avgprice,lon,lat,discount,discountdesc,addr,tel,zone,subzone) VALUES (2,'如一坊豆捞（学府街店）','太原',82,112.58110,37.80635,30,'满100减30','学府街106号','03512853333',11,9)"); 
				db.execSQL("INSERT INTO restaurants (_id,name,city,avgprice,lon,lat,discount,discountdesc,addr,tel,zone,subzone) VALUES (3,'布鲁宫法餐厅','北京',637,116.401877,39.900495,0,'无优惠','前门东大街23号','01065599200',1,8)"); 
				db.execSQL("INSERT INTO restaurants (_id,name,city,avgprice,lon,lat,discount,discountdesc,addr,tel,zone,subzone) VALUES (4,'俏江南','北京',143,116.458942,39.933132,20,'满100减20','朝阳区工体北路甲2号','01065393502',4,11)"); 
				db.execSQL("INSERT INTO restaurants (_id,name,city,avgprice,lon,lat,discount,discountdesc,addr,tel,zone,subzone) VALUES (5,'海底捞火锅（白家庄店）','北京',79,116.457589,39.928077,0,'无优惠','白家庄路甲2号','01065952982',4,11)"); 
				db.execSQL("INSERT INTO restaurants (_id,name,city,avgprice,lon,lat,discount,discountdesc,addr,tel,zone,subzone) VALUES (6,'王品台塑牛排（国贸店）','北京',281,116.451645,39.907962,0,'无优惠','建国门外大街永安里米阳大厦1楼','01065680180',4,10)"); 
				db.execSQL("INSERT INTO restaurants (_id,name,city,avgprice,lon,lat,discount,discountdesc,addr,tel,zone,subzone) VALUES (7,'利苑酒家 （金宝店）','北京',263,116.419974,39.915963,0,'无优惠','金宝街89号金宝大厦3楼','01085221212',1,1)"); 
				db.execSQL("INSERT INTO restaurants (_id,name,city,avgprice,lon,lat,discount,discountdesc,addr,tel,zone,subzone) VALUES (8,'稻香村（昌平店）','北京',19,116.416948,39.918657,0,'无优惠','东城区灯市口大街10号','01065137563',1,1)"); 
				db.execSQL("INSERT INTO restaurants (_id,name,city,avgprice,lon,lat,discount,discountdesc,addr,tel,zone,subzone) VALUES (9,'麦当劳（西单明珠店）','北京',23,116.375693,39.910769,0,'无优惠','横二条59号西单明珠商场B1楼','01066024595',2,12)"); 
				db.execSQL("INSERT INTO restaurants (_id,name,city,avgprice,lon,lat,discount,discountdesc,addr,tel,zone,subzone) VALUES (10,'小肥羊火锅','北京',69,116.420877,39.941100,30,'满100减30','东直门内大街209号','01084001669',1,3)"); 
			}
			c.close();
			c=db.rawQuery("select count(*) from dishes", null);
			c.moveToFirst();
			if (c.getInt(0)<=0){
				db.execSQL("delete from dishes", new Object[]{});
				db.execSQL("INSERT INTO dishes (restaurant,name,style,price,imgurl) VALUES (4,'XO铁板酿秋茄','家常菜',48,'http://lily.newim.net/aupages/test/c01.jpg')"); 
				db.execSQL("INSERT INTO dishes (restaurant,name,style,price,imgurl) VALUES (4,'东江千叶豆腐','招牌菜',25,'http://lily.newim.net/aupages/test/c02.jpg')"); 
				db.execSQL("INSERT INTO dishes (restaurant,name,style,price,imgurl) VALUES (4,'古法煎酿三宝','招牌菜',21,'http://lily.newim.net/aupages/test/c03.jpg')"); 
				db.execSQL("INSERT INTO dishes (restaurant,name,style,price,imgurl) VALUES (4,'火爆牛肝菌','凉菜',48,'http://lily.newim.net/aupages/test/c04.jpg')"); 
				db.execSQL("INSERT INTO dishes (restaurant,name,style,price,imgurl) VALUES (4,'椒盐百灵菇','面点',33,'http://lily.newim.net/aupages/test/c05.jpg')"); 
				db.execSQL("INSERT INTO dishes (restaurant,name,style,price,imgurl) VALUES (4,'秘制鸭仔煲','酒水',58,'http://lily.newim.net/aupages/test/c06.jpg')"); 
				db.execSQL("INSERT INTO dishes (restaurant,name,style,price,imgurl) VALUES (4,'木浆鲜椒炒虾','特色菜',53,'http://lily.newim.net/aupages/test/c07.jpg')"); 
				db.execSQL("INSERT INTO dishes (restaurant,name,style,price,imgurl) VALUES (4,'炝爆珊瑚菌','推荐菜品',45,'http://lily.newim.net/aupages/test/c08.jpg')"); 
				db.execSQL("INSERT INTO dishes (restaurant,name,style,price,imgurl) VALUES (4,'双椒石烤','家常菜',23,'http://lily.newim.net/aupages/test/c09.jpg')"); 
				db.execSQL("INSERT INTO dishes (restaurant,name,style,price,imgurl) VALUES (5,'蒜茸粉丝蒸圣瓜','家常菜',33,'http://lily.newim.net/aupages/test/c10.jpg')"); 
			}
			c.close();
		
			c=db.rawQuery("select count(*) from zone", null);
			c.moveToFirst();
			if (c.getInt(0)<=0){
				db.execSQL("delete from zone", new Object[]{});
				db.execSQL("INSERT INTO zone (_id,name,city) VALUES (1,'东城区','北京')"); 
				db.execSQL("INSERT INTO zone (_id,name,city) VALUES (2,'西城区','北京')"); 
				db.execSQL("INSERT INTO zone (_id,name,city) VALUES (3,'海淀区','北京')"); 
				db.execSQL("INSERT INTO zone (_id,name,city) VALUES (4,'朝阳区','北京')"); 
				db.execSQL("INSERT INTO zone (_id,name,city) VALUES (5,'宣武区','北京')"); 
				db.execSQL("INSERT INTO zone (_id,name,city) VALUES (6,'崇文区','北京')"); 
				db.execSQL("INSERT INTO zone (_id,name,city) VALUES (7,'丰台区','北京')"); 
				db.execSQL("INSERT INTO zone (_id,name,city) VALUES (8,'近郊','北京')"); 
				db.execSQL("INSERT INTO zone (_id,name,city) VALUES (9,'石景山区','北京')"); 
				db.execSQL("INSERT INTO zone (_id,name,city) VALUES (10,'通州区','北京')"); 
				db.execSQL("INSERT INTO zone (_id,name,city) VALUES (11,'小店区','太原')"); 
				db.execSQL("INSERT INTO zone (_id,name,city) VALUES (12,'迎泽区','太原')"); 
			}
			c.close();

			c=db.rawQuery("select count(*) from subzone", null);
			c.moveToFirst();
			if (c.getInt(0)<=0){
				db.execSQL("delete from subzone", new Object[]{});
				db.execSQL("INSERT INTO subzone (_id,name,zone) VALUES (1,'王府井',1)"); 
				db.execSQL("INSERT INTO subzone (_id,name,zone) VALUES (2,'朝阳门',4)"); 
				db.execSQL("INSERT INTO subzone (_id,name,zone) VALUES (3,'东直门',1)"); 
				db.execSQL("INSERT INTO subzone (_id,name,zone) VALUES (4,'崇文门',6)"); 
				db.execSQL("INSERT INTO subzone (_id,name,zone) VALUES (5,'东四',1)"); 
				db.execSQL("INSERT INTO subzone (_id,name,zone) VALUES (6,'安定门',1)"); 
				db.execSQL("INSERT INTO subzone (_id,name,zone) VALUES (7,'地安门',1)"); 
				db.execSQL("INSERT INTO subzone (_id,name,zone) VALUES (8,'前门',1)"); 
				db.execSQL("INSERT INTO subzone (_id,name,zone) VALUES (9,'学府街',11)"); 
				db.execSQL("INSERT INTO subzone (_id,name,zone) VALUES (10,'国贸',4)"); 
				db.execSQL("INSERT INTO subzone (_id,name,zone) VALUES (11,'三里屯',4)"); 
				db.execSQL("INSERT INTO subzone (_id,name,zone) VALUES (12,'西单',2)"); 
			}
			c.close();

			c=db.rawQuery("select count(*) from subway", null);
			c.moveToFirst();
			if (c.getInt(0)<=0){
				db.execSQL("delete from subway", new Object[]{});
				db.execSQL("INSERT INTO subway (_id,name,city) VALUES (1,'1号线','北京')"); 
				db.execSQL("INSERT INTO subway (_id,name,city) VALUES (2,'2号线','北京')"); 
				db.execSQL("INSERT INTO subway (_id,name,city) VALUES (3,'4号线','北京')"); 
				db.execSQL("INSERT INTO subway (_id,name,city) VALUES (4,'5号线','北京')"); 
				db.execSQL("INSERT INTO subway (_id,name,city) VALUES (5,'8号线','北京')"); 
				db.execSQL("INSERT INTO subway (_id,name,city) VALUES (6,'10号线','北京')"); 
				db.execSQL("INSERT INTO subway (_id,name,city) VALUES (7,'13号线','北京')"); 
			}
			c.close();

			c=db.rawQuery("select count(*) from subway_restaurant", null);
			c.moveToFirst();
			if (c.getInt(0)<=0){
				db.execSQL("delete from subway_restaurant", new Object[]{});
				db.execSQL("INSERT INTO subway_restaurant (subway,restaurant) VALUES (2,3)"); 
				db.execSQL("INSERT INTO subway_restaurant (subway,restaurant) VALUES (1,6)"); 
				db.execSQL("INSERT INTO subway_restaurant (subway,restaurant) VALUES (4,7)"); 
				db.execSQL("INSERT INTO subway_restaurant (subway,restaurant) VALUES (1,9)"); 
				db.execSQL("INSERT INTO subway_restaurant (subway,restaurant) VALUES (3,9)"); 
				db.execSQL("INSERT INTO subway_restaurant (subway,restaurant) VALUES (4,10)"); 
			}
			c.close();

			c=db.rawQuery("select count(*) from style", null);
			c.moveToFirst();
			if (c.getInt(0)<=0){
				db.execSQL("delete from style", new Object[]{});
				db.execSQL("INSERT INTO style (_id,name) VALUES (1,'晋菜')"); 
				db.execSQL("INSERT INTO style (_id,name) VALUES (2,'火锅')"); 
				db.execSQL("INSERT INTO style (_id,name) VALUES (3,'法国菜')"); 
				db.execSQL("INSERT INTO style (_id,name) VALUES (4,'川菜')"); 
				db.execSQL("INSERT INTO style (_id,name) VALUES (5,'牛排')"); 
				db.execSQL("INSERT INTO style (_id,name) VALUES (6,'粤菜')"); 
				db.execSQL("INSERT INTO style (_id,name) VALUES (7,'老北京小吃')"); 
				db.execSQL("INSERT INTO style (_id,name) VALUES (8,'快餐')"); 
				db.execSQL("INSERT INTO style (_id,name) VALUES (9,'西餐')"); 
			}
			c.close();

			c=db.rawQuery("select count(*) from style_restaurant", null);
			c.moveToFirst();
			if (c.getInt(0)<=0){
				db.execSQL("delete from style_restaurant", new Object[]{});
				db.execSQL("INSERT INTO style_restaurant (style,restaurant) VALUES (1,1)"); 
				db.execSQL("INSERT INTO style_restaurant (style,restaurant) VALUES (2,2)"); 
				db.execSQL("INSERT INTO style_restaurant (style,restaurant) VALUES (3,3)"); 
				db.execSQL("INSERT INTO style_restaurant (style,restaurant) VALUES (4,4)"); 
				db.execSQL("INSERT INTO style_restaurant (style,restaurant) VALUES (2,5)"); 
				db.execSQL("INSERT INTO style_restaurant (style,restaurant) VALUES (5,6)"); 
				db.execSQL("INSERT INTO style_restaurant (style,restaurant) VALUES (6,7)"); 
				db.execSQL("INSERT INTO style_restaurant (style,restaurant) VALUES (7,8)"); 
				db.execSQL("INSERT INTO style_restaurant (style,restaurant) VALUES (8,9)"); 
				db.execSQL("INSERT INTO style_restaurant (style,restaurant) VALUES (9,9)"); 
				db.execSQL("INSERT INTO style_restaurant (style,restaurant) VALUES (2,10)"); 
			}
			c.close();

			db.close();
		}
	}

	@Override
	protected void SendNormalRequest(MSGTYPE msgType, HashMap<String, String> params) {
		switch (msgType){
		case LOGIN:
			dologin(params);
			break;
		case REGISTER:
			doregister(params);
			break;
		case UPDATE_IMAGE:
			doupdateimg(params);
			break;
		case UPDATE_LOCATION:
			doupdatelocation(params);
			break;
		case ADD_SESSION:
			doAddSession(params);
			break;
		case ADD_ORDER:
			doAddOrder(params);
			break;
		case CHECK_NOTIFICATIONS:
			doCheckNotifications(params);
			break;
		case LOGOUT:
			machine.HandleMessage(MSGTYPE.LOGOUT, true, params);				
			break;
		case CONFIRM_INVITE:
			doConfirmInvite(params);
			break;
		case CONFIRM_ORDER:
			doConfirmOrder(params);
			break;
		case TALK:
			dotalk(params);
			break;
		}
	}

	private void dotalk(HashMap<String, String> params) {
		SQLiteDatabase db = MyHelper.get(ctx).getWritableDatabase();
		if (db!=null){
			ContentValues initValues = new ContentValues();
			initValues.put("cnt",params.get("cnt"));
			initValues.put("fromuid", Long.parseLong(params.get("user")));
			initValues.put("sessionid", Long.parseLong(params.get("session")));
			initValues.put("timestamp", new Date().getTime());
			long id=db.insert("talk", null, initValues);
			Log.d("", "talk:"+id+" sessionid:"+Long.parseLong(params.get("session")));
			params.put("id", ""+id);
			db.close();
			machine.HandleMessage(MSGTYPE.TALK, true, params);
		}
	}

	private void doConfirmOrder(HashMap<String, String> params) {
		SQLiteDatabase db = MyHelper.get(ctx).getWritableDatabase();
		if (db!=null){
			ContentValues initValues = new ContentValues();
			initValues.put("state",2);
			initValues.put("title",params.get("title"));
			db.update("sessions", initValues, "_id="+params.get("session"), null);
			
			Cursor d=db.rawQuery("select * from sessions where _id="+params.get("session"), null);
			if (d.moveToFirst()){
				Cursor c=db.rawQuery("select count(*) from sessions where state=2 and restaurant="+d.getInt(4),null);
				if (c.moveToFirst()){
					ContentValues initValues2 = new ContentValues();
					initValues2.put("ordertimes", c.getInt(0));
					db.update("restaurants", initValues2, "_id="+d.getInt(4), null);
				}
				c.close();
			}
			
			d.close();

			Cursor dishes=db.rawQuery("select dishid  from sessiondish where sessionid="+params.get("session"), null);
			while (dishes.moveToNext()){			
				d=db.rawQuery("select sum(total) from sessiondish where sessionid in (select _id from sessions where state=2) and dishid="+dishes.getLong(0), null);
				d.moveToFirst();
				ContentValues uvalues = new ContentValues();
				uvalues.put("ordertimes",d.getInt(0));
				db.update("dishes", uvalues, "_id="+dishes.getLong(0), null);
				d.close();
			}
			dishes.close();
			
			machine.HandleMessage(MSGTYPE.CONFIRM_ORDER, true, params);
			db.close();
		}
	}

	private void doConfirmInvite(HashMap<String, String> params) {
		SQLiteDatabase db = MyHelper.get(ctx).getWritableDatabase();
		if (db!=null){
			ContentValues initValues = new ContentValues();
			initValues.put("state",2);
			db.update("sessionuser", initValues, "sessionid="+params.get("session")+" and uid="+params.get("user"), null);
			machine.HandleMessage(MSGTYPE.CONFIRM_INVITE, true, params);
			db.close();
		}
	}

	private void doCheckNotifications(HashMap<String, String> params) {
		machine.HandleMessage(MSGTYPE.CHECK_NOTIFICATIONS, true, params);				
	}

	private void doAddOrder(HashMap<String, String> params) {
		SQLiteDatabase db = MyHelper.get(ctx).getWritableDatabase();
		if (db!=null){
			Cursor c=db.rawQuery( 
				     "SELECT * FROM sessions WHERE _id="+
				    		 params.get("session"), null);
			if (c.moveToFirst()){
				if (c.getInt(5)==1){
					Cursor d=db.rawQuery("select * from sessiondish where sessionid="+params.get("session")+" and dishid="+params.get("dish"), null);
					if (d.moveToFirst()){//这个菜已经点过了，就将它的个数增加1
						ContentValues values=new ContentValues();
						values.put("fromuid", Long.parseLong(params.get("uid")));
						values.put("total", d.getInt(5)+1);
						db.update("sessiondish", values, "_id="+d.getLong(0), null);
					}
					else{//没有点过，就增加一个
						db.execSQL("INSERT INTO sessiondish (sessionid,fromuid,timestamp,dishid,total)"+ 
								"VALUES ("+params.get("session")+","+params.get("uid")+","+new Date().getTime()+","+params.get("dish")+",1)");
					}
					d.close();
					
					machine.HandleMessage(MSGTYPE.ADD_ORDER, true, params);				
				}
				else{
					params.put("reason", "点餐已结束!");
					machine.HandleMessage(MSGTYPE.ADD_ORDER, false, params);				
				}
			}
			else{
				params.put("reason", "找不到聚餐信息!");
				machine.HandleMessage(MSGTYPE.ADD_ORDER, false, params);				
			}
			c.close();
			db.close();
		}
	}

	private void doAddSession(HashMap<String, String> params) {
		SQLiteDatabase db = MyHelper.get(ctx).getWritableDatabase();
		if (db!=null){
			db.execSQL("INSERT INTO sessions (fromuid,restaurant,state,timestamp)"+ 
					"VALUES ("+params.get("uid")+","+params.get("restaurant")+",1,"+new Date().getTime()+")");
			Cursor c=db.rawQuery("select last_insert_rowid()",null);
			c.moveToFirst();
			params.put("id", c.getString(0));
			c.close();
			db.close();
			machine.HandleMessage(MSGTYPE.ADD_SESSION, true, params);	
		}
	}

	public String getLocalFriendPath(String id) {
		String basedir=Environment.getExternalStorageDirectory()+"/weican/users/";
		File f=new File(basedir);
		if (!f.exists()) f.mkdirs();
		return basedir+id+".dat";
	}
	
	
	private void doupdateimg(HashMap<String, String> params) {
		
		String path=getLocalFriendPath(params.get("id"));
		try {
			byte[] in = Base64.decode(params.get("image"));
			Bitmap thumb=BitmapFactory.decodeByteArray(in, 0, in.length);
			FileOutputStream out = new FileOutputStream(path);
			thumb.compress(Bitmap.CompressFormat.PNG, 90, out);
			out.close();
			machine.HandleMessage(MSGTYPE.UPDATE_IMAGE, true, params);
		} catch (Exception e) {
			machine.HandleMessage(MSGTYPE.UPDATE_IMAGE, false, params);
			e.printStackTrace();
		} 

	}

	private void doupdatelocation(HashMap<String, String> params) {
		SQLiteDatabase db = MyHelper.get(ctx).getWritableDatabase();
		if (db!=null){
			ContentValues initValues = new ContentValues();
			initValues.put("lon",Double.parseDouble(params.get("lon")));
			initValues.put("lat",Double.parseDouble(params.get("lat")));
			initValues.put("locatime",new Date().getTime());
			db.update("users", initValues, "email='"+params.get("email")+"'", null);
			machine.HandleMessage(MSGTYPE.UPDATE_IMAGE, true, params);
			db.close();
		}
	}

	private void dologin(HashMap<String, String> params) {
		SQLiteDatabase db = MyHelper.get(ctx).getReadableDatabase();
		if (db!=null){
			Cursor c=db.rawQuery( 
				     "SELECT _id FROM users WHERE email='"+
				    		 params.get("email")+"' AND passwd='"+
				    		 params.get("passwd")+"'", null);
			if (c.moveToFirst()){
				params.put("_id", c.getString(0));
				machine.HandleMessage(MSGTYPE.LOGIN, true, params);
			}
			else{
				machine.HandleMessage(MSGTYPE.LOGIN, false, null);				
			}
			c.close();
			db.close();
		}
	}

	private void doregister(HashMap<String, String> params) {
		SQLiteDatabase db = MyHelper.get(ctx).getWritableDatabase();
		if (db!=null){
			Cursor c=db.rawQuery( 
				     "SELECT _id FROM users WHERE email='"+
				    		 params.get("email")+"'", null);
			if (c.moveToFirst()){
				params.put("_id", c.getString(0));
				params.put("reason", "重复注册!");
				machine.HandleMessage(MSGTYPE.REGISTER, false, params);
			}
			else{
				db.execSQL("INSERT INTO users (email, passwd,username)"+ 
						"VALUES ('"+params.get("email")+"', '"+params.get("passwd")+"','"+params.get("username")+"')"); 
				machine.HandleMessage(MSGTYPE.REGISTER, true, null);				
			}
			c.close();
			db.close();
		}
	}

}
